﻿using System.Diagnostics;

namespace Cngot.Extensions.Logger.Enrichers
{
    public class TraceEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            // 获取当前活动的Activity（假设存在）
            Activity currentActivity = Activity.Current;
            if (currentActivity != null)
            {
                // 添加traceId
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("TraceId", currentActivity.TraceId));

                // 如果有SpanId和ParentId，也一并添加
                if (currentActivity.IdFormat == ActivityIdFormat.W3C)
                {
                    //logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Id", currentActivity.Id));
                    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("SpanId", currentActivity.SpanId));
                    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ParentSpanId", currentActivity.ParentSpanId.ToString().Replace("0000000000000000", "")));
                    //logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ParentId", currentActivity.ParentId ?? ""));
                }
            }
        }
    }
}
